package cn.com.lyj6851.modules.activity.service.impl;

import cn.com.lyj6851.api.MyShopException;
import cn.com.lyj6851.common.service.impl.BaseServiceImpl;
import cn.com.lyj6851.common.utils.QueryHelpPlus;
import cn.com.lyj6851.dozer.service.IGenerator;
import cn.com.lyj6851.enums.BillDetailEnum;
import cn.com.lyj6851.enums.PayTypeEnum;
import cn.com.lyj6851.enums.ShopCommonEnum;
import cn.com.lyj6851.exception.BadRequestException;
import cn.com.lyj6851.modules.activity.domain.YdyUserExtract;
import cn.com.lyj6851.modules.activity.param.UserExtParam;
import cn.com.lyj6851.modules.activity.service.YdyUserExtractService;
import cn.com.lyj6851.modules.activity.service.dto.YdyUserExtractDto;
import cn.com.lyj6851.modules.activity.service.dto.YdyUserExtractQueryCriteria;
import cn.com.lyj6851.modules.activity.service.mapper.YdyUserExtractMapper;
import cn.com.lyj6851.modules.user.domain.YdyUser;
import cn.com.lyj6851.modules.user.service.YdyUserBillService;
import cn.com.lyj6851.modules.user.service.YdyUserService;
import cn.com.lyj6851.utils.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageInfo;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service
@AllArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class YdyUserExtractServiceImpl extends BaseServiceImpl<YdyUserExtractMapper, YdyUserExtract> implements YdyUserExtractService {

    private final IGenerator generator;
    private final YdyUserExtractMapper yxUserExtractMapper;
    private final YdyUserService userService;
    private final YdyUserBillService billService;


    /**
     * 开始提现
     * @param userInfo 用户
     * @param param UserExtParam
     */
    @Override
    public void userExtract(YdyUser userInfo, UserExtParam param) {
        BigDecimal extractPrice = userInfo.getBrokeragePrice();
        if(extractPrice.compareTo(BigDecimal.ZERO) <= 0) {
            throw new MyShopException("提现佣金不足");
        }

        double money = Double.valueOf(param.getMoney());
        if( extractPrice.compareTo(BigDecimal.valueOf(money)) < 0) {
            throw new MyShopException("提现佣金不足");
        }

        if(money <= 0) {
            throw new MyShopException("提现佣金大于0");
        }

        double balance = NumberUtil.sub(extractPrice.doubleValue(),money);
        if(balance < 0) {
            balance = 0;
        }

        YdyUserExtract userExtract = new YdyUserExtract();
        userExtract.setUid(userInfo.getUid());
        userExtract.setExtractType(param.getExtractType());
        userExtract.setExtractPrice(new BigDecimal(param.getMoney()));
        userExtract.setBalance(BigDecimal.valueOf(balance));

        if(StrUtil.isNotEmpty(param.getName())){
            userExtract.setRealName(param.getName());
        }else {
            userExtract.setRealName(userInfo.getNickname());
        }

        if(StrUtil.isNotEmpty(param.getWeixin())){
            userExtract.setWechat(param.getWeixin());
        }else {
            userExtract.setWechat(userInfo.getNickname());
        }

        String mark = "";

        if(PayTypeEnum.ALI.getValue().equals(param.getExtractType())){
            if(StrUtil.isEmpty(param.getAlipayCode())){
                throw new MyShopException("请输入支付宝账号");
            }
            userExtract.setAlipayCode(param.getAlipayCode());
            mark = "使用支付宝提现"+param.getMoney()+"元";
        }else if(PayTypeEnum.WEIXIN.getValue().equals(param.getExtractType())){
            if(StrUtil.isEmpty(param.getWeixin())){
                throw new MyShopException("请输入微信账号");
            }
            mark = "使用微信提现"+param.getMoney()+"元";
        }

        yxUserExtractMapper.insert(userExtract);

        //更新佣金
        YdyUser yxUser = new YdyUser();
        yxUser.setBrokeragePrice(BigDecimal.valueOf(balance));
        yxUser.setUid(userInfo.getUid());
        userService.updateById(yxUser);

        //插入流水
        billService.expend(userInfo.getUid(),"佣金提现", BillDetailEnum.CATEGORY_1.getValue(),
                BillDetailEnum.TYPE_4.getValue(),money,balance, mark);

    }

    /**
     * 累计提现金额
     * @param uid uid
     * @return double
     */
    @Override
    public double extractSum(Long uid) {
        return yxUserExtractMapper.sumPrice(uid);
    }


    //==============================================================//

    @Override
    //@Cacheable
    public Map<String, Object> queryAll(YdyUserExtractQueryCriteria criteria, Pageable pageable) {
        getPage(pageable);
        PageInfo<YdyUserExtract> page = new PageInfo<>(queryAll(criteria));
        Map<String, Object> map = new LinkedHashMap<>(2);
        map.put("content", generator.convert(page.getList(), YdyUserExtractDto.class));
        map.put("totalElements", page.getTotal());
        return map;
    }


    @Override
    //@Cacheable
    public List<YdyUserExtract> queryAll(YdyUserExtractQueryCriteria criteria){
        return baseMapper.selectList(QueryHelpPlus.getPredicate(YdyUserExtract.class, criteria));
    }


    @Override
    public void download(List<YdyUserExtractDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (YdyUserExtractDto yxUserExtract : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put(" uid",  yxUserExtract.getUid());
            map.put("名称", yxUserExtract.getRealName());
            map.put("bank = 银行卡 alipay = 支付宝wx=微信", yxUserExtract.getExtractType());
            map.put("银行卡", yxUserExtract.getBankCode());
            map.put("开户地址", yxUserExtract.getBankAddress());
            map.put("支付宝账号", yxUserExtract.getAlipayCode());
            map.put("提现金额", yxUserExtract.getExtractPrice());
            map.put(" mark",  yxUserExtract.getMark());
            map.put(" balance",  yxUserExtract.getBalance());
            map.put("无效原因", yxUserExtract.getFailMsg());
            map.put(" failTime",  yxUserExtract.getFailTime());
            map.put("-1 未通过 0 审核中 1 已提现", yxUserExtract.getStatus());
            map.put("微信号", yxUserExtract.getWechat());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    /**
     * 操作提现
     * @param resources YdyUserExtract
     */
    @Override
    public void doExtract(YdyUserExtract resources){
        if(resources.getStatus() == null){
            throw new BadRequestException("请选择审核状态");
        }

        if(ShopCommonEnum.EXTRACT_0.getValue().equals(resources.getStatus())){
            throw new BadRequestException("请选择审核状态");
        }
        YdyUserExtract userExtract = this.getById(resources.getId());
        if(!ShopCommonEnum.EXTRACT_0.getValue().equals(userExtract.getStatus())){
            throw new BadRequestException("该申请已经处理过啦！");
        }
        if(ShopCommonEnum.EXTRACT_MINUS_1.getValue().equals(resources.getStatus())){
            if(StrUtil.isEmpty(resources.getFailMsg())){
                throw new BadRequestException("请填写失败原因");
            }
            String mark = "提现失败,退回佣金"+resources.getExtractPrice()+"元";
            YdyUser yxUser = userService.getById(resources.getUid());

            double balance = NumberUtil.add(yxUser.getBrokeragePrice(),resources.getExtractPrice()).doubleValue();
            //插入流水
            billService.income(resources.getUid(),"提现失败", BillDetailEnum.CATEGORY_1.getValue(),
                    BillDetailEnum.TYPE_4.getValue(),resources.getExtractPrice().doubleValue(),balance,
                    mark,resources.getId().toString());

            //返回提现金额
            userService.incBrokeragePrice(resources.getExtractPrice(),resources.getUid());

            resources.setFailTime(new Date());

        }

        //todo 此处为企业付款，没经过测试
        /**
         boolean isTest = true;
         if(!isTest){
         YdyWechatUserDto wechatUser =  generator.convert(wechatUserService.getOne(new QueryWrapper<YdyWechatUser>().eq("uid",resources.getUid())),YdyWechatUserDto.class);
         if(ObjectUtil.isNotNull(wechatUser)){
         try {
         payService.entPay(wechatUser.getOpenid(),resources.getId().toString(),
         resources.getRealName(),
         resources.getExtractPrice().multiply(new BigDecimal(100)).intValue());
         } catch (WxPayException e) {
         throw new BadRequestException(e.getMessage());
         }
         }else{
         throw new BadRequestException("不是微信用户无法退款");
         }

         }
         **/

        this.saveOrUpdate(resources);
    }
}
